<template>
  <div class="unit-info">
    <div class="search-button">
      <el-button type="primary" @click="handleAddSave"
        ><img src="@/assets/images/Submit.png" alt="" /> 提交</el-button
      >
      <el-button @click="handleBack" color="#efbf00"
        ><img src="@/assets/images/back.png" alt="" />
        <span style="color: #ffffff">返回</span>
      </el-button>
    </div>
    <el-form
      :model="unitForm"
      ref="unitFormRef"
      :rules="queryRules"
      label-width="130px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位名称：" prop="name" label-width="130">
            <el-input
              v-model="unitForm.name"
              placeholder="请输入单位名称"
              clearable
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行政区划：" prop="region">
            <el-cascader
              v-model="unitForm.region"
              placeholder="请选择行政区划"
              :options="options"
              @change="handlerregion"
              @visible-change="getpolicestation"
              filterable
              clearable
              style="width: 100%"
              :props="areaprops"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="0">
        <el-col :span="12">
          <el-form-item label="所属行业：" prop="industryId">
            <el-select
              v-model="unitForm.industryId"
              placeholder="请选择所属行业"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in supervisorList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue * 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址：" prop="address">
            <el-input
              v-model="unitForm.address"
              placeholder="请点击地图选择详细地址"
              clearable
              maxlength="25"
              disabled
            >
              <template #append>
                <img
                  src="@/assets/images/map.png"
                  alt=""
                  style="width: 34px; cursor: pointer"
                  @click="selectaddress"
                /> </template
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位级别：" prop="levelId" label-width="130">
            <el-select
              v-model="unitForm.levelId"
              placeholder="请选择单位级别"
              clearable
              class="search-input"
              style="width: 100%"
            >
              <el-option
                v-for="dict in unitlevelList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue * 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位类型：" prop="typeId">
            <el-select
              v-model="unitForm.typeId"
              placeholder="请选择单位类型"
              clearable
              class="search-input"
              style="width: 100%"
            >
              <el-option
                v-for="dict in unittypeList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue * 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="0">
        <el-col :span="12">
          <el-form-item label="所属派出所：" prop="policeStationId">
            <el-select
              v-model="unitForm.policeStationId"
              placeholder="请选完行政区划再选择所属派出所"
              clearable
              class="search-input"
              style="width: 100%"
            >
              <el-option
                v-for="dict in policeList"
                :key="dict.deptId"
                :label="dict.deptName"
                :value="dict.deptId * 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="社会信用代码：" prop="unifiedSocialCreditCode">
            <el-input
              v-model="unitForm.unifiedSocialCreditCode"
              placeholder="请输入"
              clearable
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="单位负责人:" prop="leader" label-width="130">
            <el-input
              v-model="unitForm.leader"
              placeholder="填写姓名"
              clearable
              maxlength="10"
              class="search-input"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" prop="leaderPhone" label-width="10">
            <el-input
              v-model="unitForm.leaderPhone"
              placeholder="填写联系方式"
              clearable
              maxlength="11"
              class="search-input"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单位简介：" prop="institutionDescription">
            <el-input
              type="textarea"
              maxlength="200"
              v-model="unitForm.institutionDescription"
              placeholder="请输入"
              clearable
              class="search-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 详细地址地图选择弹窗 -->
    <el-dialog
      title="详细地址选择"
      v-model="isshowmap"
      width="1200px"
      append-to-body
    >
      <div style="width: 1160px; height: 600px">
        <Selectmap
          @handlerselect="handlermarker"
          :projectForm="unitForm"
          :pagestatus="pagestatus"
          v-if="isshowmap"
        ></Selectmap>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Selectmap from "./selectmap";
import {
  addinstitution,
  editinstitution,
  selectDeptListByUser,
} from "@/api/erp/unit";
import { getAreaList } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";

const props = defineProps({
  // 操作类型
  showdialog: {
    type: Boolean,
    default: false,
  },
  //行业主管下拉
  supervisorList: {
    type: Array,
    default: [],
  },
  //单位类型数据
  unittypeList: {
    type: Array,
    default: [],
  },
  //单位级别下拉
  unitlevelList: {
    type: Array,
    default: [],
  },
});

const userStore = useUserStore();

const emit = defineEmits(["refreshList"]);

let pagestatus = ref(null);

let options = ref([]);

const areaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 3,
            // disabled: level < 3, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};
//省市区校验规则
const provinceValidate = (rule, value, callback) => {
  // const { province, city, area } = projectForm.value;
  // if (!province || !city || !area) {
  //   callback(new Error("请选择省市区"));
  // } else {
  //   callback();
  // }
  const { region } = unitForm.value;
  console.log("region.length", region.length);
  if (region.length == 0) {
    console.log("zhixn");
    callback(new Error("请选择省市区街道"));
  } else if (region.length < 4) {
    console.log(2);
    callback(new Error("请选择到街道"));
  } else {
    callback();
  }
};

const unitForm = ref({
  region: [],
});
const queryRules = ref({
  name: [{ required: true, message: "请输入单位名称", trigger: "blur" }],
  industryId: [
    { required: true, message: "请选择行业主管部门", trigger: "change" },
  ],
  address: [
    {
      required: true,
      message: "请输入详细地址",
      trigger: ["blur", "change"],
    },
  ],
  levelId: [{ required: true, message: "请选择单位级别", trigger: "change" }],
  region: [
    {
      required: true,
      validator: provinceValidate,

      trigger: "change",
    },
  ],
  typeId: [{ required: true, message: "请选择单位类型", trigger: "change" }],
  unifiedSocialCreditCode: [
    { required: true, message: "请输入社会信用代码", trigger: "blur" },
  ],
  leader: [
    { required: true, message: "请填写使用单位联系人", trigger: "blur" },
  ],
  leaderPhone: [
    {
      required: true,
      message: "请填写使用单位联系人联系方式",
      trigger: "blur",
    },
    {
      pattern: /^1\d{10}$/,
      message: "请输入正确的电话号码",
      trigger: "blur",
    },
  ],
  policeStationId: [
    { required: true, message: "请选择所属派出所", trigger: "change" },
  ],
});

//详细地址地图选择弹窗显隐
let isshowmap = ref(false);

//所属派出所
const policeList = ref([]);

/**
 * @description: 地图详细地址
 */
const selectaddress = () => {
  isshowmap.value = true;
};
//地图详细地址
const handlermarker = (pointInfo) => {
  isshowmap.value = false;
  unitForm.value.address = pointInfo.address;
  unitForm.value.longitude = pointInfo.lng;
  unitForm.value.latitude = pointInfo.lat;
};

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (value) {
    switch (value.length) {
      case 1:
        unitForm.value.provinceId = value[0];
        break;
      case 2:
        unitForm.value.provinceId = value[0];
        unitForm.value.cityId = value[1];
        break;
      case 3:
        unitForm.value.provinceId = value[0];
        unitForm.value.cityId = value[1];
        unitForm.value.zoneId = value[2];
        break;
      case 4:
        unitForm.value.provinceId = value[0];
        unitForm.value.cityId = value[1];
        unitForm.value.zoneId = value[2];
        unitForm.value.streetId = value[3];
        break;
      default:
        break;
    }
  } else {
    unitForm.value.region = [];
    unitForm.value.provinceId = null;
    unitForm.value.cityId = null;
    unitForm.value.zoneId = null;
    unitForm.value.streetId = null;
  }
};

/**
 * @description: 提交
 * @param {Object} customerFormRef 客户表单引用
 */
const unitFormRef = ref(null);
const handleAddSave = async () => {
  await unitFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          console.log("unitForm.value", unitForm.value);
          let Fun;
          if (pagestatus.value == "edit") {
            Fun = editinstitution;
          } else {
            Fun = addinstitution;
          }
          Fun(unitForm.value).then((res) => {
            if (res.code === 200) {
              emit("update:showUnitadd", false);
              emit("refreshList");
              ElMessage.success(res.msg);
              unitForm.value = {
                region: [],
              };
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  });
};

const handleBack = () => {
  emit("update:showUnitadd", false);
};

//处理编辑
const handleEdit = (row) => {
  console.log("row", row);
  row.region = [];
  row.provinceId && row.region.push(row.provinceId);
  row.cityId && row.region.push(row.cityId);
  row.zoneId && row.region.push(row.zoneId);
  row.streetId && row.region.push(row.streetId);
  unitForm.value = row;
  pagestatus.value = "edit";
};

/**
 * @description:  获取派出所
 * @param {Number} id
 */
const getpolicestation = () => {
  let obj = {
    deptType: 1,
    provinceId: unitForm.value.provinceId,
    cityId: unitForm.value.cityId,
    zoneId: unitForm.value.zoneId,
    streetId: unitForm.value.streetId,
  };
  selectDeptListByUser(obj).then((res) => {
    policeList.value = res.data;
  });
};

onMounted(() => {
  if (userStore.deptType == 0 || userStore.deptType == 1) {
    userStore.provinceId && unitForm.value.region.push(userStore.provinceId);
    userStore.cityId && unitForm.value.region.push(userStore.cityId);
    userStore.zoneId && unitForm.value.region.push(userStore.zoneId);
    userStore.streetId && unitForm.value.region.push(userStore.streetId);
    handlerregion(unitForm.value.region);
    getpolicestation();
    if (userStore.deptType == 1) {
      unitForm.value.policeStationId = userStore.deptId;
    }
    if (userStore.industryManagementId) {
      unitForm.value.industryId = userStore.industryManagementId;
    }
  }
});

defineExpose({
  handleEdit,
});
</script>

<style scoped lang="scss">
.unit-info {
  margin-top: 20px;
}
:deep(.el-input-group__append) {
  padding: 0px 2px !important;
}
</style>
